import json
import random
import re
import util.ReadData as ReadData
import VecDB
import util.Embedding as Embedding
from util.llm import get_confusing_sentences

Num = 3

course_list = ReadData.get_course_summary('data/rec_data/course_summary_concepts.json')

vec_db = VecDB.read_vecdb('data/rec_data/concepts_emb.faiss')

def calculate_concept_overlap(original_concepts, recommended_concepts):
    """计算推荐课程与原课程知识点的重合度"""
    original_set = set(original_concepts)
    recommended_set = set(recommended_concepts)
    overlap = original_set.intersection(recommended_set)
    overlap_ratio = len(overlap) / len(original_set) if original_set else 0
    return list(overlap), overlap_ratio

def rag_rec(video_name, confusing_text, original_concepts):
    """
    video_name: 课程名称
    confusing_text: 用于向大模型询问疑惑句子的文本（例如学生反馈或课程字幕）
    original_concepts: 原课程的概念列表（从 JSON 中提取）
    """
    query_v = Embedding.get_embedding(confusing_text)

    D, idx_s = vec_db.search(query_v, k=5)
    rec_list = ["以下是可推荐课程的候选列表:\n"]
    for idx in idx_s[0]:
        rec_list.append(
            f"课程视频名称: {course_list[idx]['name']}\n"
            f"课程视频内容概要: {course_list[idx]['summary']}\n"
        )

    recommended_concepts = []
    for idx in idx_s[0]:
        course_concepts_str = course_list[idx]['concept']
        split_concepts = re.split(r'\d+\.\s*', course_concepts_str)
        split_concepts = [s for s in split_concepts if s]
        recommended_concepts.extend(split_concepts)

    recommended_concepts = list(set(recommended_concepts))

    overlap, overlap_ratio = calculate_concept_overlap(original_concepts, recommended_concepts)

    return recommended_concepts, rec_list, confusing_sentences, overlap, overlap_ratio

data = []
for i in range(3):
    course = course_list[i]
    course_concepts_str = course['concept']
    original_concepts = re.split(r'\d+\.\s*', course_concepts_str)
    original_concepts = [s for s in original_concepts if s]

    selected_concepts = random.sample(original_concepts, min(Num, len(original_concepts)))
    confusing_sentences = get_confusing_sentences(selected_concepts, course['text'])

    question, res, rec_list, confusing_sentences, overlap, overlap_ratio = rag_rec(
        course['name'],
        [confusing_sentences],
        original_concepts
    )
    data.append({
        "res": res,
        "context": original_concepts,
        "confusing_sentences": confusing_sentences,
        "concept_overlap": overlap,
        "overlap_ratio": overlap_ratio
    })

with open('data/result.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

for item in data:
    print("推荐结果:", item["res"])
    print("上下文:", item["context"])
    print("可能引起疑惑的句子:", item["confusing_sentences"])
    print("知识点重合:", item["concept_overlap"])
    print("知识点重合度:", item["overlap_ratio"])
    print("\n" + "=" * 50 + "\n")
